package com.awake.auth.controller;

import com.awake.auth.service.ISysUserService;
import com.awake.common.exception.OaException;
import com.awake.common.jwt.JwtHelper;
import com.awake.common.result.Result;
import com.awake.common.result.ResultCodeEnum;
import com.awake.common.utils.MD5;
import com.awake.model.system.SysUser;
import com.awake.vo.system.LoginVo;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
@RequiredArgsConstructor
public class IndexController {

    private final ISysUserService sysUserService;

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("login")
    public Result<Map<String, Object>> login(@RequestBody LoginVo loginVo) {
        SysUser sysUser = sysUserService.selectByUsername(loginVo.getUsername());

        if (Objects.isNull(sysUser)) {
            throw new OaException(ResultCodeEnum.USER_NOT_EXIST);
        }

        String encrypt = MD5.encrypt(loginVo.getPassword());
        if (!Objects.equals(encrypt, sysUser.getPassword())) {
            throw new OaException(ResultCodeEnum.PASSWORD_ERROR);
        }

        if (!Objects.equals(sysUser.getStatus(), 1)) {
            throw new OaException(ResultCodeEnum.USER_FORBIDDEN);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", JwtHelper.createToken(sysUser.getId(), sysUser.getUsername()));
        return Result.ok(map);
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("info")
    public Result<Map<String , Object>> info(HttpServletRequest request) {
        String username = JwtHelper.getUsername(request.getHeader("token"));
        return Result.ok(sysUserService.getUserInfo(username));
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("logout")
    public Result logout() {
        return Result.ok();
    }
}
